<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.insuranceName"
        placeholder="机构名称搜索"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />&nbsp;&nbsp;&nbsp;
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <br />
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="success"
        icon="el-icon-plus"
        @click="handleCreate"
      >
        新增
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="tableData"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :row-class-name="tableRowClassName"
    >
      <el-table-column label="机构名称" prop="id" align="center" width="280">
        <template slot-scope="{ row }">
          <span>{{ row.insuranceName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="APP展示名称" class-name="status-col" width="300">
        <template slot-scope="{ row }">
          <span>{{ row.exhibitionName }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="服务天数" class-name="status-col" width="280">
        <template slot-scope="{ row }">
          <span>{{ row.serviceDays }}</span>
        </template>
      </el-table-column>
      <el-table-column label="当天咨询人数" class-name="status-col" width="280">
        <template slot-scope="{ row }">
          <span>{{ row.consultingService }}</span>
        </template>
      </el-table-column> -->
      <el-table-column
        label="负责人通知"
        align="center"
        min-width="120"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-switch
            v-model="row.leadSwitch"
            active-text="开"
            inactive-text="关"
            active-color="#13ce66"
            inactive-color="#ff4949"
            align="center"
            @change="changeLeadSwitch(row)"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        min-width="260"
      >
        <template slot-scope="{ row }">
          <el-button type="info" size="mini" @click="addBatch(row)">
            添加协议
          </el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="warning" size="mini" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.current"
      :limit.sync="listQuery.size"
      @pagination="loanList"
    />

    <!-- <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :before-close="cancel">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="loan"
        label-position="left"
        label-width="110px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="保险名称" prop="insuranceName">
          <el-input v-model="loan.insuranceName" />
        </el-form-item>
        <el-form-item label="展示名称" prop="exhibitionName">
          <el-input v-model="loan.exhibitionName"/>
        </el-form-item>
        <el-form-item label="服务天数" prop="serviceDays">
          <el-input v-model="loan.serviceDays" />
        </el-form-item>
        <el-form-item label="当天服务人数" prop="consultingService">
          <el-input v-model="loan.consultingService" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel()">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          确认
        </el-button>
      </div>
    </el-dialog> -->

    <el-dialog
      title="新增"
      :visible.sync="dialogFormVisible"
      :before-close="cancel"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="loan"
        label-position="left"
        label-width="110px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="机构名称" prop="insuranceName">
          <el-input v-model="loan.insuranceName" />
        </el-form-item>
        <el-form-item label="APP展示名称" prop="exhibitionName">
          <el-input v-model="loan.exhibitionName" />
        </el-form-item>
        <el-form-item label="logo">
          <el-upload
            ref="upload"
            :action="action"
            limit="1"
            :auto-upload="true"
            :on-success="handleSuccess"
            :on-error="handleError"
            :file-list="fileList"
            :show-file-list="false"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="负责人手机号">
          <el-input v-model="loan.phoneNumber" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel()">
          取消
        </el-button>
        <el-button type="primary" @click="createData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="编辑"
      :visible.sync="dialogFormVisible2"
      :before-close="cancel2"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="loan1"
        label-position="left"
        label-width="110px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="机构名称" prop="insuranceName">
          <el-input v-model="loan1.insuranceName" readonly />
        </el-form-item>
        <el-form-item label="App展示名称" prop="exhibitionName">
          <el-input v-model="loan1.exhibitionName" />
        </el-form-item>
        <el-form-item label="logo">
          <el-upload
            ref="upload"
            :action="action"
            limit="1"
            :auto-upload="true"
            :on-success="handleSuccess1"
            :on-error="handleError"
            :file-list="fileList"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="负责人手机号">
          <el-input v-model="loan1.phoneNumber" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel2()">
          取消
        </el-button>
        <el-button type="primary" @click="updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="添加协议"
      :visible.sync="dialogFormVisible1"
      :before-close="cancel1"
    >
      <el-form
        ref="form"
        :rules="formRules"
        :inline="true"
        :model="form"
        label-width="80px"
      >
        <div v-for="(item, index) in form.dynamicItem" :key="index">
          <el-form-item
            label="协议名称"
            :prop="'dynamicItem.' + index + '.protocolName'"
            :rules="{
              required: true,
              message: '协议名称不能为空',
              trigger: 'blur',
            }"
          >
            <el-input v-model="item.protocolName"></el-input>
          </el-form-item>
          <el-form-item
            label="协议链接"
            :prop="'dynamicItem.' + index + '.protocolUrl'"
            :rules="{
              required: true,
              message: '协议链接不能为空',
              trigger: 'blur',
            }"
          >
            <el-input v-model="item.protocolUrl"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="info"
              @click="deleteItem(item, index)"
              v-show="index != 0"
              >删除</el-button
            >
          </el-form-item>
          <el-button @click="addItem" type="primary">增加</el-button>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel1">
          取消
        </el-button>
        <el-button type="primary" @click="submitBatch">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import { addloan, deleteById, editloan, loanList } from "@/api/sys";
import {
  InsuranceList,
  InsuranceAdd,
  InsuranceUpdate,
  addBatch,
  findList,
  deleteBx,
} from "@/api/advertising";
import waves from "@/directive/waves"; // waves directive
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
export default {
  name: "Sysloanlist",
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      action: process.env.VUE_APP_BASE_API.split('/')[0] + '//' + process.env.VUE_APP_BASE_API.split('/')[2] + '/api/foundation/api/file/upload',
      form: {
        protocolName: "",
        protocolUrl: "",
        dynamicItem: [
          // { crmId: 0, crmNickname: "", protocolName: "", protocolUrl: "",crmType:2 },
        ],
      },
      smsNotice: false,
      limitNum: 1,
      fileList: [],
      comment: "",
      tableData: [],
      total: 0,
      tableKey: 0,
      listQuery: {
        current: 1,
        insuranceName: "",
        size: 10,
      },
      loan: {
        id: 0,
        exhibitionName: "",
        insuranceName: "",
        phoneNumber: "",
        logo:""
      },
      loan1: {
        id: 0,
        exhibitionName: "",
        insuranceName: "",
        phoneNumber: "",
        leadNotice:0,
        logo:""
      },
      dialogFormVisible: false,
      dialogFormVisible1: false,
      dialogFormVisible2: false,
      dialogStatus: "",
      textMap: {
        update: "修改",
        create: "新增",
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        insuranceName: [
          { required: true, message: "保险名称必填", trigger: "blur" },
        ],
        exhibitionName: [
          { required: true, message: "展示名称必填", trigger: "blur" },
        ],
        serviceDays: [
          { required: true, message: "服务天数必填", trigger: "blur" },
        ],
        consultingService: [
          { required: true, message: "当天服务人数必填", trigger: "blur" },
        ],
      },
      downloadLoading: false,
      listLoading: false,
      imageUrl: "",
      pushState: false,
      status: false,
      leadSwitch:false
    };
  },
  created() {
    this.loanList();
  },
  methods: {
    // 文件上传失败时的钩子
    handleError(err, file, fileList) {
      this.$message.error(err.msg)
    },
    submitUpload() {
      this.$refs.upload.submit()
    },
    handleSuccess(res, file, fileList) {
      this.loan.logo = res.data // 服务器返回的文件地址
      this.fileList[0] = file
      this.imageUrl = res.data
      this.$message({
        message: '文件上传成功',
        type: 'success'
      })
      this.$refs.upload.clearFiles()// 清楚上次上传记录
    },
    handleSuccess1(res, file, fileList) {
      this.loan1.logo = res.data // 服务器返回的文件地址
      this.fileList[0] = file
      this.imageUrl = res.data
      this.$message({
        message: '文件上传成功',
        type: 'success'
      })
      this.$refs.upload.clearFiles()// 清楚上次上传记录
    },
    exceedFile(files, fileList) {
      this.$notify.warning({
        title: '警告',
        message: `只能选择 ${
          this.limitNum
        } 个文件，当前共选择了 ${files.length + fileList.length} 个`
      })
    },
    cancel1() {
      (this.form.dynamicItem = []); (this.dialogFormVisible1 = false);
    },
    async addBatch(row) {
      const res = await findList({ crmId: row.id, crmType: 2 });
      if (res.data.code == 200) {
        let listData = res.data.data;
        if (listData.length == 0) {
          this.form.dynamicItem = [
            {
              crmId: 0,
              crmNickname: "",
              protocolName: "",
              protocolUrl: "",
              crmType: 2,
            },
          ];
        } else {
          listData.forEach((item) => {
            this.form.dynamicItem.push(item);
          });
        }
      }
      this.dialogFormVisible1 = true;
      this.form.dynamicItem[0].crmId = row.id;
      this.form.dynamicItem[0].crmNickname = row.nickName;
    },
    submitBatch() {
      addBatch(this.form.dynamicItem).then((res) => {
        if (res.data.code === 200) {
          this.$notify({
            title: "Success",
            message: "添加成功",
            type: "success",
            duration: 2000,
          });
        } else {
          this.$notify({
            title: "fail",
            message: res.data.msg,
            type: "fail",
            duration: 2000,
          });
        }
        this.cancel1();
      });
    },
    addItem() {
      this.form.dynamicItem.push({
        crmId: this.form.dynamicItem[0].crmId,
        crmNickname: this.form.dynamicItem[0].crmNickname,
        crmType: 2,
        protocolName: "",
        protocolUrl: "",
      });
    },
    deleteItem(item, index) {
      this.form.dynamicItem.splice(index, 1);
    },
    // 获取列表
    async loanList(listQuery) {
      const res = await InsuranceList(this.listQuery);
      res.data.data.records.forEach((element) => {
        element.leadSwitch=element.leadNotice==1
      });
      this.tableData = res.data.data.records;
      this.total = res.data.data.total;
    },
    changeLeadSwitch(row){
      this.loan1 = row;
      if (this.loan1.leadSwitch) {
        this.loan1.leadNotice = 1;
      } else {
        this.loan1.leadNotice = 0;
      }
      InsuranceUpdate(this.loan1).then((res) => {
        if (res.data.code === 200) {
          this.$notify({
            title: "Success",
            message: "更新成功",
            type: "success",
            duration: 2000,
          });
          this.loanList(this.listQuery);
        } else {
          this.$notify({
            title: "fail",
            message: "更新失败",
            type: "fail",
            duration: 2000,
          });
        }
      });
    },
    handleFilter() {
      this.listQuery.current = 1;
      this.loanList(this.listQuery);
    },
    cancel() {
      this.dialogFormVisible = false;
      this.loanList();
      this.fileList=[]
    },
    cancel2() {
      this.dialogFormVisible2 = false;
      this.loanList();
      this.fileList=[]
    },

    handleCreate() {
      this.dialogFormVisible = true;
      this.loan.insuranceName = "";
      this.loan.exhibitionName = "";
      this.loan.phoneNumber="";
      this.imageUrl="";
      // 刷新表单数据验证提示
      // this.$nextTick(() => {
      //   this.$refs["dataForm"].clearValidate();
      // });
    },
    createData() {
      const that = this;
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          InsuranceAdd(this.loan).then((res) => {
            if (res.data.code === 200) {
              that.$notify({
                title: "Success",
                message: "新增成功",
                type: "success",
                duration: 2000,
              });
              that.loanList(that.listQuery);
            } else {
              this.$notify({
                title: "fail",
                message: res.data.msg,
                type: "fail",
                duration: 2000,
              });
            }
            this.dialogFormVisible = false;
          });
        }
      });
    },
    async handleUpdate(row) {
      this.loan1 = row;
      this.loan1.id = row.id;
      this.imageUrl=row.logo;
      this.dialogFormVisible2 = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    updateData() {
      const that = this;
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          InsuranceUpdate(that.loan1).then((res) => {
            if (res.data.code === 200) {
              that.$notify({
                title: "Success",
                message: "Update Successfully",
                type: "success",
                duration: 2000,
              });
              that.loanList(that.listQuery);
            } else {
              that.$notify({
                title: "fail",
                message: res.data.msg,
                type: "fail",
                duration: 2000,
              });
            }
            this.dialogFormVisible2 = false;
          });
        }
      });
    },
    handleDelete(row, index) {
      var that = this;
      this.$confirm("删除提示！", "确认删除吗？", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }).then(() => {
        deleteBx({ id: row.id }).then((res) => {
          if (res.data.code === 200) {
            that.$notify({
              title: "Success",
              message: "删除成功",
              type: "success",
              duration: 2000,
            });
            that.loanList(that.listQuery);
          } else {
            this.$notify({
              title: "错误",
              message: res.data.msg,
              type: "fail",
              duration: 2000,
            });
          }
        });
      });
    },

    getSortClass: function(key) {
      const sort = this.listQuery.sort;
      return sort === `+${key}` ? "ascending" : "descending";
    },
  },
};
</script>

<style scoped>
.pic {
  width: 150px;
  margin-top: 10px;
  margin-left: 10px;
}
.ok {
  margin-left: 10px;
  margin-top: 10px;
  font-weight: 5 00;
  color: rgb(35, 248, 124);
}
.fail {
  margin-left: 10px;
  margin-top: 10px;
  font-weight: 5 00;
  color: rgb(240, 174, 76);
}
.info {
  margin-left: 10px;
  margin-top: 10px;
  font-weight: 5 00;
}
.info-name {
  margin-left: 50px;
  margin-top: 10px;
  color: rgb(172, 176, 177);
}
.title {
  margin-top: 10px;
  margin-left: 10px;
  font-size: 20px;
  font-weight: 400;
}
.box {
  margin-top: 10px;
  width: 100%;
  border: solid rgb(138, 219, 230) 2px;
}
.nick {
  font-size: 30px;
  font-weight: 600;
}
.link-top {
  margin-left: 10px;
  margin-top: 10px;
  width: 100%;
  height: 2px;
  border-top: solid rgb(138, 219, 230) 2px;
}
.link-title {
  margin-left: 10px;
  margin-top: 10px;
  width: 80px;
  height: 2px;
  border-top: solid rgb(172, 176, 177) 2px;
}
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
